package com.heima.esdata;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.utils.EsDataApplication;
import com.heima.utils.mapper.ApArticleContentMapper;
import com.heima.utils.mapper.ApArticleMapper;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest(classes = EsDataApplication.class)
@RunWith(SpringRunner.class)
public class ImportArticleData {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Test
    public void importAllData() throws IOException {
        String indexName="app_info_article";
        boolean hasIndex=existIndex(indexName);
        if(hasIndex){
            deleteIndex(indexName);
        }
        createIndex(indexName,"{\n" +
                "      \"properties\" : {\n" +
                "        \"authorId\" : {\n" +
                "          \"type\" : \"integer\"\n" +
                "        },\n" +
                "        \"content\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_smart\"\n" +
                "        },\n" +
                "        \"id\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        },\n" +
                "        \"images\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        },\n" +
                "        \"layout\" : {\n" +
                "          \"type\" : \"short\"\n" +
                "        },\n" +
                "        \"publishTime\" : {\n" +
                "          \"type\" : \"date\"\n" +
                "        },\n" +
                "        \"title\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_smart\"\n" +
                "        }\n" +
                "      }\n" +
                "    }");
        //查询并删除状态不为1 且上架的文章信息
        List<ApArticle> apArticles = apArticleMapper.loadArticleList();
        //批量将文章数据 插入到es索引库中
        BulkRequest bulkRequest = new BulkRequest(indexName);
        for (ApArticle apArticle : apArticles) {
            Map<String,Object>map=new HashMap<>();
            map.put("id",String.valueOf(apArticle.getId()));
            map.put("publishTime",apArticle.getPublishTime());
            map.put("layout",apArticle.getLayout());
            map.put("images",apArticle.getImages());
            map.put("authorId",apArticle.getAuthorId());
            map.put("title",apArticle.getTitle());
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(
                    ApArticleContent::getArticleId, apArticle.getId()
            ));
            if(apArticleContent != null){
                map.put("content",apArticleContent.getContent());
            }
            IndexRequest request = new IndexRequest();
            //设置索引库中文章文档的id
            request.id(apArticle.getId()+"");
           request.source(JSON.toJSONString(map) ,XContentType.JSON);
           bulkRequest.add(request);
        }
        client.bulk(bulkRequest,RequestOptions.DEFAULT);
    }
      //删除索引库
    private void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        client.indices().delete(request,RequestOptions.DEFAULT);
    }

    //创建指定索引库
    private void createIndex(String indexName, String mapping) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.mapping(mapping, XContentType.JSON);
        client.indices().create(request,RequestOptions.DEFAULT);
    }

    //判断是否包含指定索引库
    private boolean existIndex(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        try {
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            return exists;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
